package com.retail.task;

import cn.hutool.core.util.ObjectUtil;
import com.retail.core.task.RetailQuartzJobBean;
import com.retail.shop.entity.request.RetailShopRequest;
import com.retail.shop.entity.vo.RetailShopVo;
import com.retail.shop.enums.ShopSourceEnums;
import com.retail.shop.service.RetailShopService;
import com.retail.system.service.CronTriggersService;
import com.retail.system.service.CronTriggersSynchroTimeService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 抖音shop
 *
 * @author Administrator
 */
@Component
@Slf4j
public class DouyinShopJobTask extends RetailQuartzJobBean {
    @Autowired
    private CronTriggersService cronTriggersService;

    @Autowired
    private CronTriggersSynchroTimeService cronTriggersSynchroTimeService;
    

    @Autowired
    private RetailShopService retailShopService;


    @Override
    protected CronTriggersService getCronTriggersService() {
        return cronTriggersService;
    }

    @Override
    protected CronTriggersSynchroTimeService getcronTriggersSynchroTimeService() {
        return cronTriggersSynchroTimeService;
    }

    @Override
    public void task(JobExecutionContext jobExecutionContext) {
        new Thread(() -> {
            Integer page = 1;
            Integer size = 10;

            List<RetailShopRequest> shops = retailShopService.syncTokTikShopList(page, size);
            while (shops.size() > 0) {
                operaShop(shops);
                if (shops.size() >= size) {
                    page++;
                    shops = retailShopService.syncTokTikShopList(page, size);
                }
            }
        }).start();
    }


    /**
     * 处理商户数据
     *
     * @param shops
     */
    private void operaShop(List<RetailShopRequest> shops) {
        shops.forEach(shop -> {
            String poiId = shop.getPoiId();
            RetailShopVo retailShopVo = retailShopService.getmodelByPoiIdAndSource(poiId, ShopSourceEnums.DY_TYPE.getValue());
            if (ObjectUtil.isNotEmpty(retailShopVo)) {
                shop.setId(retailShopVo.getId());
                retailShopService.update(shop);
            } else {
                retailShopService.save(shop);
            }
        });
    }
}
